package com.ys.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class ReqUtil {
	public static String ADMIN_TOKEN = "admin_token";
	

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-real-ip"); // 先从nginx自定义配置获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static Long getAdminId(HttpServletRequest request) {
    	String tokenflag = ADMIN_TOKEN;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
//                System.out.println(cookie.getName() + "---" + cookie.getValue());
                if (cookie.getName().equals(tokenflag)) {
                    String value = cookie.getValue();
                    if (!StringUtils.isEmpty(value)) {
                        String id = value.substring(value.lastIndexOf("_") + 1, value.length());
                        return Long.valueOf(id);
                    }
                }
            }
        }
        return 0L;
    }

    public static Long getSysRoleId(HttpServletRequest request) {
    	String tokenflag = ADMIN_TOKEN;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(tokenflag)) {
                    String value = cookie.getValue();
                    if (!StringUtils.isEmpty(value)) {
                        String id = value.substring(value.indexOf("_") + 1, value.lastIndexOf("_"));
                        return Long.valueOf(id);
                    }
                }
            }
        }
        return 0L;
    }
    
    public static void main(String[] args) {
		String value = "aa_2_1";
		System.out.println(value.substring(value.indexOf("_") + 1, value.lastIndexOf("_")));
		String valueSub = value.substring(0, value.lastIndexOf("_"));
		System.out.println(valueSub);
	}
}
